package com.jumi.microservice.transfers;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransOrderQueryModel;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.jumi.microservice.config.AliPayConfig;
import com.jumi.microservice.constant.TransferEnum;
import com.jumi.microservice.dto.PayTransferQueryRequest;
import com.jumi.microservice.dto.PayTransferRequest;
import com.jumi.microservice.transfers.common.BaseTransfer;
import com.jumi.microservice.transfers.common.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Scw
 * @Date 2019-09-29 10:34
 */
@Component
public class AliPayTransfer extends BaseTransfer {
    private Logger log = LoggerFactory.getLogger(AliPayTransfer.class);
    @Resource
    AliPayConfig alipayConfig;

    @Override
    public Context createContext(PayTransferRequest request) {
        AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
        model.setOutBizNo(request.getOrderSn());
        model.setPayeeType("ALIPAY_LOGONID");
        model.setPayeeAccount(request.getAccountId());
        model.setAmount(new BigDecimal(request.getAmount())
                .divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN)
                .toString());
        model.setPayeeRealName(request.getRealName());
        model.setRemark(request.getDesc());

        Context context = new Context();
        context.setModel(model);
        return context;
    }

    @Override
    public Map<String, String> doProcess(Context context) {
        AlipayFundTransToaccountTransferModel model = context.getModel();
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getServerUrl(), alipayConfig.getAppId(), alipayConfig.getPrivateKey(),
                "json", "utf-8", alipayConfig.getPublicKey(), "RSA2");
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        request.setBizModel(model);
        //返回信息接收
        Map<String, String> returnMap = new HashMap<>();
        try {
            AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
            String parameters = "{" +
                    "\"amount\":\"" + model.getAmount() +
                    "\",\"out_biz_no\":\"" + model.getOutBizNo() +
                    "\",\"payee_account\":\"" + model.getPayeeAccount() +
                    "\",\"payee_real_name\":\"" + model.getPayeeRealName() +
                    "\",\"payee_type\":\"" + model.getPayeeType() +
                    "\",\"remark\":\"" + model.getRemark()
                    + "\"}";
            returnMap.put("parameters", parameters);
            returnMap.put("code", response.getCode());
            returnMap.put("msg", response.getMsg());
            if (response.isSuccess()) {
                returnMap.put("out_biz_no", response.getOutBizNo());
                returnMap.put("order_id", response.getOrderId());
                returnMap.put("pay_date", response.getPayDate());
            } else {
                returnMap.put("sub_code", response.getSubCode());
                returnMap.put("sub_msg", response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    @Override
    public Integer getType() {
        return TransferEnum.ALI_PAY_TRANSFER.getCode();
    }

    /**
     * 转账查询接口
     */
    @Override
    public String transferQuery(PayTransferQueryRequest payTransferQueryRequest) {
        String transferQueryResult = "查询异常";
        AlipayFundTransOrderQueryModel model = new AlipayFundTransOrderQueryModel();
        model.setOrderId(payTransferQueryRequest.getOrderId());
        model.setOutBizNo(payTransferQueryRequest.getOutBizNo());
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getServerUrl(), alipayConfig.getAppId(), alipayConfig.getPrivateKey(),
                "json", "utf-8", alipayConfig.getPublicKey(), "RSA2");
        AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
        request.setBizModel(model);
        try {
            AlipayFundTransOrderQueryResponse response = alipayClient.execute(request);
            log.info("transferQuery result>" + response.getBody());
            //返回信息接收
            Map<String, String> returnMap = new HashMap<>();
            String parameters = "{" +
                    "\"order_id\":\"" + model.getOrderId() +
                    "\",\"out_biz_no\":\"" + model.getOutBizNo()
                    + "\"}";
            returnMap.put("parameters", parameters);
            returnMap.put("code", response.getCode());
            returnMap.put("msg", response.getMsg());
            if (response.isSuccess()) {
                returnMap.put("order_id", response.getOrderId());
                returnMap.put("status", response.getStatus());
                returnMap.put("pay_date", response.getPayDate());
                returnMap.put("arrival_time_end", response.getArrivalTimeEnd());
                returnMap.put("order_fee", response.getOrderFee());
                returnMap.put("fail_reason", response.getFailReason());
                returnMap.put("out_biz_no", response.getOutBizNo());
                returnMap.put("error_code", response.getErrorCode());
            } else {
                returnMap.put("sub_code", response.getSubCode());
                returnMap.put("sub_msg", response.getSubMsg());
            }
            transferQueryResult = "查询结果：" + returnMap.toString();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info("查询结果：{}", transferQueryResult);
        return transferQueryResult;
    }
}
